<template>
    <ContentWrap>
        <template #header>
            <el-space wrap>
                <mdp-hi-query :column-configs="columnConfigs" v-model="hiQueryParams" @change="onHiQueryParamsChange" title="高级查询，定制任意复杂的查询条件"/>
                <el-button icon="zoom-out" @click="searchReset()" title="重置查询条件并查询"/>
                <el-button icon="download" @click="export2Excel()" title="导出查询结果到excel"/>
                <mdp-table-configs :column-configs="columnConfigs" v-model="checkedColumns"/>
                <el-button type="success" ref="kanbanBtn" plain @click="openKanban('kanbanDlg')" title="看板">板</el-button>
                <span v-if="currOpType=='mng'">
                    <el-button :disabled="disBtn('delBtn') || !checkBtnQx('delBtn',menuDefId) || this.sels.length===0 || load.del==true" type="danger" v-loading="load.del" @click="batchDel" icon="delete"  plain title="取消项目与产品的关联关系">移出</el-button>
                    &nbsp;<xm-project-select  title="选择更多项目加入产品" width="300px"  show-style="origin" placeholder="选择更多项目加入" :autoSelect="false" @change2="onProjectSelect"/>

                    
                </span>
                <span v-else-if="currOpType=='select' &&  this.multiple==true">
                    <el-button :disabled="disBtn('selectBtn') || this.sels.length===0" type="primary" @click="selectListConfirm" icon="check"  plain />
                </span>
            </el-space>
        </template>
        <el-space wrap>
            <MdpSelectTag v-model="tagIds" placeholder="标签" @change="(e)=>filters.tagIds=(e?('*'+e+'*'):'')" initLoad/>  

            <el-input v-model="filters['res.projectId']"  placeholder="项目编号" clearable title="支持>、<、 >=、<=、!=、*字符*、$IS NULL、$IN 1,2,3、$between 1,5等操作符"/>
            <el-input v-model="filters['p.projectName']"  placeholder="项目名称" clearable title="支持>、<、 >=、<=、!=、*字符*、$IS NULL、$IN 1,2,3、$between 1,5等操作符"/>
            <el-button v-loading="load.list" :disabled="load.list==true" @click="searchTableDatas()" icon="search" type="primary" plain />
        </el-space>
    </ContentWrap>
    <!--列表 XmProductProjectLink -->
    <el-table ref="table" v-adaptive :data="tableDatas" @sort-change="sortChange" highlight-current-row v-loading="load.list" border @selection-change="selsChange" @row-click="rowClick" style="width: 100%;">
        <el-table-column  type="selection" width="55" fixed="left" v-if="currOpType=='mng' || this.multiple==true"/>
        <el-table-column sortable prop="projectName" width="300" fixed="left" label="项目名称" col-prefix="p.">
            <template #default="scope">
                <el-popover placement="right-start" :width="200" show-after="200">
                    <template #reference>
                        <el-link @click="currOpType=='mng'?intoInfo(scope.row):intoInfo(scope.row)" type="primary">
                            {{ (scope.$index + 1) }}&nbsp; {{ scope.row.projectName }}
                        </el-link>
                    </template>
                    <template #default>
                        <el-space wrap>
                            <el-button v-if="currOpType=='mng'" @click="intoInfo(scope.row, scope.$index)" icon="document-copy" type="warning">进入项目视图</el-button>
                         </el-space>
                    </template>
                </el-popover>
            </template>
        </el-table-column>
        <!-- 可编辑字段格式
        <el-table-column prop="objType"  label="对象类型" min-width="120" show-overflow-tooltip col-type="String" v-if="showCol('objType')">
            <template #default="scope">
                    <mdp-select itemCode="objType" show-style="tag" v-model="scope.row.objType" :maxlength="50" @change="editSomeFields(scope.row,'objType',$event)" :disabled="!someOpen||disField"/>
            </template>
        </el-table-column>
        -->
 
        <el-table-column prop="initRate" label="进度" width="200" sortable  col-prefix="p.">
						<template #default="scope">

							<div style="display:flex;">
								<div style="width:3em;">
									{{getProgress(scope.row)}} %
								</div>
								<el-button  id="guider-four" type="text" circle plain icon="video-play"  title="统计项目的工作量、进度、需求、bugs等数据"  @click.stop="loadTasksToXmProjectState( scope.row)"/>

								<el-tag v-if="getPlanRealProgress(scope.row)>0" type="warning" effect="dark">超前{{ getPlanRealProgress(scope.row) }}%</el-tag>
								<el-tag v-else-if="getPlanRealProgress(scope.row)<0" type="danger" effect="dark">落后{{ 0-getPlanRealProgress(scope.row) }}%</el-tag>
								<el-tag v-else-if="getProgress(scope.row)>0" effect="dark" type="success" class="check">正常</el-tag>
								<el-tag v-else-if="getProgress(scope.row)==0" effect="dark" type="info">未开始 </el-tag>
							</div>

 						</template>
					</el-table-column>  
					<el-table-column prop="tagIds" label="标签" width="120" sortable >
                        <template #default="scope">
                            <MdpSelectTag show-style="tag" split="," v-model="scope.row.tagIds" placeholder="标签" multiple @change="editXmProjectSomeFields(scope.row,'tagIds',$event)"/>  
                        </template>
                    </el-table-column>
					<el-table-column prop="iterationCnt" label="迭代数" sortable min-width="120"  col-prefix="p."/>
					<el-table-column prop="menuCnt" label="需求数" sortable min-width="120"  col-prefix="p.">
						<template #default="scope">
							<span title="完成的需求数 / 需求总数 ">{{scope.row.menuCnt>0?scope.row.menuFinishCnt+'&nbsp;/&nbsp;'+scope.row.menuCnt:''}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="taskCnt" label="任务数" sortable min-width="120"  col-prefix="p.">
						<template #default="scope">
							<span title="完成的任务数 / 任务总数 ">{{ ((scope.row.taskFinishCnt||0)+(scope.row.taskSetCnt||0)+(scope.row.taskCloseCnt||0))+'&nbsp;/&nbsp;'+(scope.row.taskCnt||0)}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="bugCnt" label="问题数" sortable min-width="120"  col-prefix="p.">
						<template #default="scope">
							<span title="关闭的问题数 / 问题总数 ">{{scope.row.bugCnt>0?scope.row.closedBugs+'&nbsp;/&nbsp;'+scope.row.bugCnt:''}}</span>
						</template>
						</el-table-column>
 
 					    <el-table-column prop="initWorkload" label="预估工时" width="120"  show-overflow-tooltip sortable  col-prefix="p."/>
						<el-table-column prop="estimateWorkload" label="应完成工时" width="150"  show-overflow-tooltip sortable  col-prefix="p."/>
						<el-table-column prop="sumActWorkload" label="已完成总工时" width="150"  show-overflow-tooltip sortable  col-prefix="p."/>
						
						<el-table-column prop="budgetWorkload" label="任务预估工时" width="150"  show-overflow-tooltip sortable  col-prefix="p."/>
						<el-table-column prop="actWorkload" label="任务完成工时" width="150"  show-overflow-tooltip sortable  col-prefix="p."/> 
						 
						<el-table-column prop="mactWorkload" label="非报工工时" width="150"  show-overflow-tooltip sortable  col-prefix="p."/> 
                        <el-table-column prop="projectId"  label="项目编号" min-width="120" show-overflow-tooltip col-type="String" v-if="showCol('projectId')" sortable  col-prefix="p."/>
                        <el-table-column prop="productId" label="项目集编号" min-width="120" show-overflow-tooltip  col-type="String" v-if="showCol('productId')" sortable  col-prefix="p."/>

        <el-table-column label="操作" width="100" fixed="right" v-if="currOpType=='select' && this.multiple!=true" >
            <template #default="scope">
                <el-button   type="primary" @click="selectConfirm(scope.row)" icon="check"/>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
        layout="slot,total, sizes, prev, next,pager,jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :page-sizes="[10,20, 50, 100, 500]"
        :current-page="pageInfo.pageNum"
        :page-size="pageInfo.pageSize"
        :total="pageInfo.total"
        style="float:right;"
    /> 
    <MdpDialog ref="kanbanDlg" fullscreen :title="menuDefName">
        <MdpTableKanban
            :hiddenCfg="{delBtn:false,addBtn:false}"
            @del="(d,cb)=>handleDel(d)"
            @plus="(cb)=>showAdd()"
            @edit="(d,cb)=>showEdit(d)"
            v-model="tableDatas"
            :columnConfigs="columnConfigs"
            :itemKey="pkNames[0]"
            :contentFun="(item)=>item.projectName"
        />
         <!--
            <template #toolbar="{element}">
                <MdpSelect showStyle="tag" itemCode="xmProductPstatus" disabled v-model="element.pstatus"/>
            </template>
        </MdpTableKanban>
        -->
    </MdpDialog>
</template>

<script>

import { MdpTableMixin } from '@/components/mdp-ui/mixin/MdpTableMixin.js';
import * as XmProductProjectLinkApi from '@/api/xm/core/xmProductProjectLink';  
import { listXmProject,editXmProjectSomeFields} from '@/api/xm/core/xmProject';
import { mapState } from 'pinia'
import { useUserStore } from '@/store/modules/user' 
import { useXmStore } from '@/store/modules/xm'  
import {  loadTasksToXmProjectState} from '@/api/xm/core/xmProjectState';

export default {
    name:'XmProductProjectLinkMng',
    mixins:[MdpTableMixin],
    components: { 
    },
    computed: {
        ...mapState(useUserStore,['userInfo']), 
        ...mapState(useXmStore,['xmProduct'])
    },
    props:{
         // 是否开启editSomeField模式
         someOpen:{
            type: Boolean,
            default: true,
        },
    },
    data() {
        return {
            menuDefId:'',//menu_def.id 菜单表菜单编号，用于按钮权限判断
            menuDefName:'',//menu_def.name 功能名称，用于导出excel等文件名
            pkNames:["productId","projectId"],//表格主键的java属性名称，驼峰命名，默认为id,支持多主键
            currOpType:'mng',//表格 mng-综合管理具有最大权限，所有按钮可动、detail-只看不能操作
            filters:{//查询参数

            },
            defaultFilters:{//默认查询参数,第一次打开界面的时候用到，恢复默认值的时候用到

            },
            pageInfo:{//分页数据
                total:0,//服务器端收到0时，会自动计算总记录数，如果上传>0的不自动计算。
                pageSize: this.pageable?10:1500,//每页数据
                count:false,//是否需要重新计算总记录数
                pageNum:1,//当前页码、从1开始计算
                orderFields:[],//排序列 如 ['sex','student_id']，必须为数据库字段
                orderDirs:[]//升序 asc,降序desc 如 性别 升序、学生编号降序 ['asc','desc']
            },
            //增删改查(含批量)接口
            apis:{
                list: listXmProject,
                add: XmProductProjectLinkApi.addXmProductProjectLink,
                del: XmProductProjectLinkApi.delXmProductProjectLink,
                edit: XmProductProjectLinkApi.editXmProductProjectLink,
                editSomeFields: XmProductProjectLinkApi.editSomeFieldsXmProductProjectLink,
                batchAdd: XmProductProjectLinkApi.batchAddXmProductProjectLink,
                batchDel: XmProductProjectLinkApi.batchDelXmProductProjectLink,
                batchEdit: XmProductProjectLinkApi.batchEditXmProductProjectLink,
            }
        }
    },
    methods: {
         //页面初始化需要配置的特殊逻辑写这里
          initCurrData(){
             this.searchTableDatas();
          },

          /**
           * 检查参数是否满足调用后台接口的条件
           *
           * @param params 提交给后台的参数池,map类型
           * @returns true / false
           */
          preQueryParamCheck(params){
              params.linkProductId=this.xmProduct?.id||'xxxx'
              return true;
          },

          //页面数据加载完后需要对数据进行加工处理的
          afterList(tableDatas,isOk,apiName){
            if(tableDatas && tableDatas.length>0){
                tableDatas.forEach(e=>e.productId=this.xmProduct?.id||'')
            }
            
          },
          editXmProjectSomeFields(row,f,tagIds){
            editXmProjectSomeFields({'$pks':[row.id],tagIds:tagIds}).then(res=>{
                var tips= res.tips;
                if( tips.isOk ){
                    this.$notify.success("执行成功") 
                }else{
                    this.searchTableDatas();
                    this.$notify.error(tips.msg)
                }
            })
          },
          /**
           * 对修改的字段进行判断，返回false ,将取消更新数据库
           * @param {*} row 当前选中的行
           * @param {*} fieldName 修改的字段名
           * @param {*} $event 修改后的值
           * @param {*} params 将要提交服务器的参数
           * @returns true/false 返回false ,将取消更新数据库
           */
          editSomeFieldsCheck(row,fieldName,$event,params){
              params[fieldName]=$event
              return true;
          }, 
			getProgress(project){
				var planRate=0;
				if(!project.estimateWorkload||!project.initWorkload){
					planRate= 0;
					return planRate;
				}
				planRate= Math.round(project.estimateWorkload/project.initWorkload*100);
				return planRate
			},
			getPlanRealProgress(project){
				var planRate=0;
				if(!project.estimateWorkload||!project.initWorkload){
					planRate= 0;
					return planRate;
				}
				planRate=project.estimateWorkload/project.initWorkload*100;
				return  Math.round((project.initRate||0)-planRate)
			},
            //进入项目视图界面
			intoInfo(row) { 
				this.$router.push({ name:'projectOverview', query: {projectId:row.projectId} }) 
			}, 
            onProjectSelect(project){
				this.$confirm('确认建立与项目【'+project.name+'】的关联关系吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.load.del=true; 
                    var link={projectId:project.id,productId:this.xmProduct.id}
					XmProductProjectLinkApi.addXmProductProjectLink(link).then((res) => {
						this.load.del=false;
						var tips=res.tips;
						if( tips.isOk ){
							this.pageInfo.count=true;
							this.searchTableDatas();
						}
						this.$notify({ message: tips.msg, type: tips.isOk?'success':'error'});
					}).catch( err  => this.load.del=false );
				});
			},
			loadTasksToXmProjectState(row){

                var params={projectId:row.projectId}
                loadTasksToXmProjectState(params).then((res) => {
                    this.load.edit=false;
                    var tips=res.tips;

                    if( tips.isOk ){
                        this.$notify.success("执行成功")
                        this.searchTableDatas();
                    }else{
                        this.$notify.error(tips.msg)
                    }
                }).catch( err  => this.load.edit=false );
            }, 
    },
    mounted() {

    }
}

</script>

<style scoped>
</style>